package cn.hy.dataSync.config;

import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.regex.Pattern;


public class Transformer implements Serializable {

    private static final long serialVersionUID = 5853284786277208559L;

    private static final Pattern PATTERN = Pattern.compile("^[a-zA-Z_$][a-zA-Z_$0-9]*$");

    /**
     * 目标列
     */
    private String column;

    /**
     * 转换器
     * <p>
     * 大多数时候都是直接映射，readerConfig:column_a -> writerConfig:column_b
     * 只有当非直接映射时，才需要表达式计算
     * *    readerConfig:column_a + 4 -> writerConfig:column_b
     * *    readerConfig:jsonExtract(column_a,"$.a") -> writerConfig:column_b
     * <p>
     * 尽管表达式计算性能很高，但相比于手写 java 实现肯定是有损耗的。
     * 所以，在 job 的预处理阶段可以区分开来，避免没必要的性能损耗
     */
    private String expression;

    /**
     * 是否直接映射
     */
    private boolean directMapping;

    public String getColumn() {
        return column;
    }

    public Transformer setColumn(String column) {
        this.column = column;
        return this;
    }

    public String getExpression() {
        return expression;
    }

    public Transformer setExpression(String expression) {
        this.expression = expression;
        if (!directMapping) {
            this.directMapping = isDirectMapping(expression);
        }
        return this;
    }

    public boolean isDirectMapping() {
        return directMapping;
    }

    public Transformer setDirectMapping(boolean directMapping) {
        this.directMapping = directMapping;
        return this;
    }

    private static boolean isDirectMapping(String expression) {
        if (StringUtils.isBlank(expression)) {
            return true;
        }
        return PATTERN.matcher(expression).matches();
    }
}
